let express = require('express');

let router = express.Router();
let md5 = require('md5-node');
let bodyParser = require('body-parser');
let DB = require('../../modules/db');

router.use(bodyParser.urlencoded({ extended: false }));
// app.use(bodyParser.urlencoded({ extended: false }));
router.use(bodyParser.json());

router.get('/',function (req,res) {

    // res.send("用户登录");
    res.render('admin/login');
})

router.post('/doLogin',function (req,res) {
    let username = req.body.username;
    let password = md5(req.body.password);
    console.log(username);
    console.log(password);
    // 1.获取数据
    //2.连接数据库查询数据
    DB.find('user',{
        username:username,
        password:password
    },function(err,data){
        if(data.length>0){
            console.log('登录成功');
            //保存用户信息
            req.session.userInfo=data[0];

            res.redirect('/admin/product');  /*登录成功跳转到商品列表*/

        }else{
            //console.log('登录失败');
            res.send("<script>alert('登录失败');location.href='/admin/login'</script>");
        }
    })
})

router.get("/loginOut",function (req,res) {

    //销毁session
    req.session.destroy(err=>{
        if(err)
            console.log(err);
        else{
            res.redirect('/admin/login');
        }
    })
})
module.exports = router;//暴露路由 router 模块
